// import { isAliPay } from '../validate'
import request from '../request'
import authority from '../authority'
import qs from 'kuan-utils/lib/qs'

// 主动登陆地址
function getLoginUrl(customBack) {
  const baseUrl = 'https://www.luzhongkuan.cn/wx/login'
  let backUrl = customBack
  if (!backUrl) {
    const { origin, pathname, search } = window.location
    backUrl = encodeURIComponent(`${origin}${pathname}${search}`)
  }
  return `${baseUrl}?back=${backUrl}`
}

// 去除alipay_code
function refreshPage(url) {
  const { origin, pathname } = window.location
  const searchData = qs.parse(url || window.location.href)
  const { code } = searchData
  if (code) {
    delete searchData.code
    const href = url.split('?')[0] || `${origin}${pathname}`
    const hasSearch = !!Object.keys(searchData).length
    const finalUrl = hasSearch ? `${href}?${qs.stringify(searchData)}` : href
    window.location.replace(finalUrl)
  }
}

// 保存用户信息
async function toLogin(backUrl) {
  const { code } = qs.parse(window.origin.href)

  if (code) {
    // 登陆返回code，获取用户信息
    try {
      const user = await request({
        url: `/wx/code/${code}`
      })
      const { nickname, headimgurl: avatar, id } = user
      authority.set({ token: Date.now(), nickname, avatar, id })
    } catch (e) { }

    refreshPage(backUrl)
  } else if (!authority.get()) {
    // 直接登陆
    authority.set({ isLogin: true })
    const loginUrl = getLoginUrl(backUrl)

    window.location.replace(loginUrl)
  } else {
    return Promise.reject(new Error('登陆失败，401会再次登陆'))
  }
  return true
}

// 登陆
export function login(backUrl) {
  // 已经登陆或者不是支付宝 直接return
  // if (authority.get() || !isAliPay) return
  console.log(111)
  const { id } = authority.get() || {}
  console.log(id)
  if (id) return true
  // 保存用户信息
  return toLogin(backUrl)
}

// 401强制登陆
export function login401() {
  authority.set('')
  login()
}
